# -*- coding: utf-8 -*-
from rest_framework.response import Response
from rest_framework.viewsets import ModelViewSet

from goods.models import SKU, GoodsCategory, SPU, SPUSpecification
from meiduo_admin.serializers.sku import SKUSerializer, SKUCategorySerializer, SPUSimpleSerializer, \
    SPUSpecificationSerializer
from meiduo_admin.utils import PageNum


class SKUViewSet(ModelViewSet):
    # 指定序列化器
    serializer_class = SKUSerializer
    # 指定分页器
    pagination_class = PageNum

    # 重写get_queryset，根据keyword进行查询
    def get_queryset(self):
        keyword = self.request.query_params.get('keyword')

        if keyword == '' or keyword is None:
            return SKU.objects.all()
        else:
            return SKU.objects.filter(name=keyword)

    def categorie(self, request):
        # 查询三级分类信息
        data = GoodsCategory.objects.filter(subs=None)
        # 序列化返回三级分类
        ser = SKUCategorySerializer(data, many=True)
        return Response(ser.data)

    def goodssimple(self, request):
        # 查询spu表数据
        data = SPU.objects.all()
        # 序列化返回spu数据
        ser = SPUSimpleSerializer(data, many=True)
        return Response(ser.data)

    def spuspecification(self, request, pk):
        # 查询spu商品的所有规格
        data = SPUSpecification.objects.filter(spu_id=pk)
        # 序列化返回
        ser = SPUSpecificationSerializer(data, many=True)
        return Response(ser.data)
